package com.lyj.springcloud.order.controller;

import com.lyj.springcloud.entities.CommonResult;
import com.lyj.springcloud.entities.Payment;
import com.lyj.springcloud.lb.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    /**
     * 支付服务url单机版
     *      static final String PAYMENT_URL = "http://localhost:8001";
     */
    static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";// 通过restTemplate负载均衡

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancer loadBalancer;

    @Autowired
    RestTemplate restTemplate;


    @GetMapping("/get/mylb")
    public String getPayment() {
        // 获取注册中心可用的服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0 ) {
            return null;
        }
        ServiceInstance server = loadBalancer.instances(instances);
        URI uri = server.getUri();
        return restTemplate.getForObject(uri + "/payment/mylb" ,
                String.class );
    }
}
